package com.ruoyi.controller;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.domain.Article;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.domain.Leader;
import com.ruoyi.service.ILeaderService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 领导班子Controller
 *
 * @author ruoyi
 * @date 2024-12-17
 */
@RestController
@RequestMapping("/leader/leader")
public class LeaderController extends BaseController
{
    @Autowired
    private ILeaderService leaderService;

    @Autowired
    private FileStorageService fileStorageService;//注入实列

    @Anonymous
    @PostMapping("/imagePath/{id}")
    public AjaxResult uploadFile(@PathVariable Long id, @RequestParam MultipartFile file) throws Exception {
        try {
            // 检查文件是否为空
            if (file.isEmpty()) {
                return AjaxResult.error("上传文件为空");
            }

            // 获取 base-path
            String basePath = "leaderImage/"; // 直接在这里设置基础路径，或者从配置文件中读取

            // 指定oss保存文件路径
            String objectName = basePath + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd")) + "/" + file.getOriginalFilename();
            // 上传图片，成功返回文件信息
            FileInfo fileInfo = fileStorageService.of(file).setPath(objectName).upload();

            // 设置返回结果
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", fileInfo.getUrl());
            ajax.put("fileName", fileInfo.getUrl());  // 注意：这里的值要改为url，前端访问的地址,需要文件的地址 而不是文件名称
            ajax.put("newFileName", fileInfo.getUrl());
            ajax.put("originalFilename", file.getOriginalFilename());

            // 创建Article对象并设置ID和filePath
            Leader leader = new Leader();
            leader.setLeaderId(id); // 你需要实现一个方法来生成唯一的ID，或者从其他地方获取ID
            leader.setImage(fileInfo.getUrl());

            // 更新数据库中的filePath字段
            boolean result = leaderService.updateById(leader);
            if (!result) {
                return AjaxResult.error("更新文件路径失败");
            }

            return ajax;

        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 查询领导班子列表
     */
//    @PreAuthorize("@ss.hasPermi('leader:leader:list')")
    @Anonymous
    @GetMapping("/list")
    public TableDataInfo list(Leader leader)
    {
        startPage();
        List<Leader> list = leaderService.selectLeaderList(leader);
        return getDataTable(list);
    }

    /**
     * 导出领导班子列表
     */
    @PreAuthorize("@ss.hasPermi('leader:leader:export')")
    @Log(title = "领导班子", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Leader leader)
    {
        List<Leader> list = leaderService.selectLeaderList(leader);
        ExcelUtil<Leader> util = new ExcelUtil<Leader>(Leader.class);
        util.exportExcel(response, list, "领导班子数据");
    }

    /**
     * 获取领导班子详细信息
     */
//    @PreAuthorize("@ss.hasPermi('leader:leader:query')")
    @Anonymous
    @GetMapping(value = "/{leaderId}")
    public AjaxResult getInfo(@PathVariable("leaderId") Long leaderId)
    {
        return success(leaderService.selectLeaderByLeaderId(leaderId));
    }

    /**
     * 新增领导班子
     */
    @PreAuthorize("@ss.hasPermi('leader:leader:add')")
    @Log(title = "领导班子", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Leader leader)
    {
        return toAjax(leaderService.insertLeader(leader));
    }

    /**
     * 修改领导班子
     */
    @PreAuthorize("@ss.hasPermi('leader:leader:edit')")
    @Log(title = "领导班子", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Leader leader)
    {
        return toAjax(leaderService.updateLeader(leader));
    }

    /**
     * 删除领导班子
     */
    @PreAuthorize("@ss.hasPermi('leader:leader:remove')")
    @Log(title = "领导班子", businessType = BusinessType.DELETE)
	@DeleteMapping("/{leaderIds}")
    public AjaxResult remove(@PathVariable Long[] leaderIds)
    {
        return toAjax(leaderService.deleteLeaderByLeaderIds(leaderIds));
    }
}
